package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.exception.CategoryBusinessException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Lff
 * @date 2022/2/27
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
        implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page<Category> findAllByPage(Integer page, Integer pageSize) {
        Page<Category> pages = new Page<>(page, pageSize);
        //添加排序条件
        LambdaQueryWrapper<Category> qw = Wrappers.lambdaQuery(Category.class);
        //设置排序规则
        qw.orderByAsc(Category::getSort);
        qw.orderByDesc(Category::getUpdateTime);
        //查询分页数据
        categoryMapper.selectPage(pages, qw);

        return pages;
    }

    /**
     * 添加分类
     *
     * @param category
     * @return
     */
    @Override
    public boolean addCategory(Category category) {
        int insert = 0;
        try {
            insert = categoryMapper.insert(category);
        } catch (Exception e) {
            String msg = "套餐分类：" + category.getName() + "已存在！";
            if (category.getType() == 1) {
                msg = "菜品分类：" + category.getName() + "已存在！";
            }
            throw new CategoryBusinessException(msg);
        }
        return insert == 1;
    }

    /**
     * 删除指定id的分类
     *
     * @param id
     */
    @Override
    public void delById(Long id) {
        int i = categoryMapper.countCategory(id);
        if (i > 0) {
            throw new CategoryBusinessException("该分类下有" + i + "条记录，不能删除！");
        }
        categoryMapper.deleteById(id);
    }

    /**
     * 修改分类信息
     *
     * @param category
     */
    public void updateCategory(Category category) {
        categoryMapper.updateById(category);
    }

    /**
     * 获取所有菜品或者套餐的分类
     *
     * @param
     * @return
     */
    @Override
    public List<Category> getCategoryList(Category category) {
        LambdaQueryWrapper<Category> qw = Wrappers.lambdaQuery(Category.class);
        qw.eq(category.getType() != null, Category::getType, category.getType());
        qw.orderByAsc(Category::getType);
        qw.orderByAsc(Category::getSort);
        qw.orderByDesc(Category::getUpdateTime);
        List<Category> categories = categoryMapper.selectList(qw);
        return categories;
    }

}
